package kr.co.hk.local;

import java.util.ArrayList;
import java.util.List;

import kr.co.hk.R;
import kr.co.hk.util.MapUtil;
import kr.co.hk.util.MyLocationListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LocalMain extends Activity implements OnClickListener {

	private String bestProvider; // 현재 위치값을 가져오기위한 프로바이더. (network, gps)
	private LocationManager locM; // 위치 매니저
	private LocationListener locL; // 위치 리스너
	private Location currentLocation; // 현재 위치
	private String latlng = "";

	private String addrSplit = "";
	private JSONObject jObject;
	private boolean isStatus;
	
	private EditText et;
	private ArrayList<String> matches;
	private static final int REQUEST_CODE = 1234;
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.local_main);
		et = (EditText) findViewById(R.id.etNaverSearch);
		Button btnNaverSearch = (Button) findViewById(R.id.btnNaverSearch);
		Button btnCoffee = (Button) findViewById(R.id.image1);
		Button btnDepart = (Button) findViewById(R.id.image2);
		Button btnSauna = (Button) findViewById(R.id.image3);
		Button btnBank = (Button) findViewById(R.id.image4);
		Button btnHosp = (Button) findViewById(R.id.image5);
		Button btnBook = (Button) findViewById(R.id.image6);
		Button btnRest = (Button) findViewById(R.id.image7);
		Button btnPharm = (Button) findViewById(R.id.image8);

		Button btnVoiceSearch = (Button) findViewById(R.id.btnVoiceSearch);

		PackageManager pm = getPackageManager();
		List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
				RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
		if (activities.size() != 0) {
			btnVoiceSearch.setOnClickListener(this);
		} else {
			btnVoiceSearch.setEnabled(false);
			btnVoiceSearch.setText("Not Rec");
		}

		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE);
		criteria.setAltitudeRequired(false);
		criteria.setBearingRequired(false);
		criteria.setCostAllowed(true);
		criteria.setSpeedRequired(true);
		criteria.setPowerRequirement(Criteria.POWER_LOW);

		// 위치 매니저를 시스템으로부터 받아온다.
		locM = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

		// 사용가능한 적절한 프로바이더를 받아온다.
		// network (보통 3G망,Wifi AP 위치정보)또는 gps 둘중 하나로 설정된다.
		bestProvider = locM.getBestProvider(new Criteria(), true);

		// 기기에 가지고 있는 마지막 위치정보로 현재위치를 초기 설정한다.
		currentLocation = locM.getLastKnownLocation(bestProvider);

		// 위치 리스너 초기화
		locL = new MyLocationListener();
		// 위치 매니저에 위치 리스너를 셋팅한다.
		// 위치 리스너에서 10000ms (10초) 마다 100미터 이상 이동이 발견되면 업데이트를 하려한다.
		locM.requestLocationUpdates(bestProvider, 10000, 100, locL);


		latlng = currentLocation.getLatitude() + ","
				+ currentLocation.getLongitude();
		isStatus = getAddrSplit(latlng);
		btnNaverSearch.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String etStr = et.getText().toString();
				if (etStr.equals("")) {
					toast("검색어를 입력하세요!");
				} else {
					search(etStr);
				}
			}
		});

		btnCoffee.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				search("커피전문점");
			}
		});
		btnBank.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				search("은행");
			}
		});

		btnBook.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				search("서점");

			}
		});

		btnDepart.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				search("백화점");

			}
		});
		btnHosp.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				search("병원");

			}
		});
		btnPharm.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				search("약국");

			}
		});
		btnRest.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				search("레스토랑");

			}
		});

		btnSauna.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				search("찜질방");
			}
		});
	}

	public void onClick(View v) {
		if (v.getId() == R.id.btnVoiceSearch) {
			startVoiceRecognitionActivity();
		}
	}

	private void startVoiceRecognitionActivity() {
		try {
			Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
			intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
					RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
			intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
					"주변 시설 검색어를 말하세요!");
			startActivityForResult(intent, REQUEST_CODE);
		} catch (ActivityNotFoundException ex) {
			Toast.makeText(LocalMain.this, "Activity Not Found",
					Toast.LENGTH_LONG).show();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
			matches = data
					.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
			search(matches.get(0));
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	private void search(String nQuery) {
		if (isStatus) {
			Intent intent = new Intent(LocalMain.this,
					LocalLocationMapView.class);
			intent
					.putExtra("currentLocationLat", currentLocation
							.getLatitude());
			intent.putExtra("currentLocationLng", currentLocation
					.getLongitude());
			intent.putExtra("addrSplit", addrSplit);
			intent.putExtra("nQuery", nQuery);
			startActivity(intent);
		} else {
			toast("현재위치를 못찾았습니다.\n 검색을 할수 없습니다.");
		}
	}

	private boolean getAddrSplit(String latlng) {

		boolean isStatus = false;
		String url = "http://maps.google.co.kr/maps/api/geocode/json?latlng="
				+ latlng + "&sensor=false";
		MapUtil mapUtil = new MapUtil();
		String jString = mapUtil.getResultConn(url);
		try {
			addrSplit = "";
			jObject = new JSONObject(jString);
			if (!jObject.equals(null)) {
				String status = jObject.getString("status");
				if (status.equals("OK")) {
					JSONArray resultArr = new JSONArray(jObject
							.getString("results"));
					String formatted_address = resultArr.getJSONObject(0)
							.getString("formatted_address");

					String[] addresArr = formatted_address.split(" ");
					int maxCnt = 3;
					if (addresArr.length > 5) {
						maxCnt = 4;
					} else {
						maxCnt = 3;
					}
					for (int j = 1; j < maxCnt; j++) {
						addrSplit += addresArr[j] + " ";

					}
					isStatus = true;
				} else {
					isStatus = false;
				}

			} else {
				isStatus = false;
			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
		return isStatus;

	}

	private void toast(String text) {
		Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
	}

}